package com.ruoyi.consumer.utils.redis;

import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author: lizhouwei
 * @ date : 2023/11/20
 * @description:
 */
@Component
public class AgentCache {

    @Autowired
    private RedisCache redisCache;

    //将代理申请存入redis
    //上级userId，申请者信息，申请者有多个
    public void cacheAgentApply(Integer superId, Integer userId, Integer agentId) {
        List<Integer> cacheList = redisCache.getCacheList("agentApply:" + superId + ":" + agentId + ":");
        if (cacheList != null) {
            redisCache.deleteObject("agentApply:" + superId + ":" + agentId + ":");
            cacheList.add(userId);
        } else {
            cacheList = new ArrayList<>();
            cacheList.add(userId);
        }

        redisCache.setCacheList("agentApply:" + superId + ":" + agentId + ":", cacheList);
    }

    //从redis中获取代理申请
    public List<Object> getAgentApply(Integer superId) {
        // 获取所有匹配的键名
        Set<String> keys = (Set<String>) redisCache.keys("agentApply:" + superId + ":*");
        System.out.println("keys打印出所有的键名:" + keys); // 打印出所有的键名
        List<Object> list = new ArrayList<>();
        // 遍历并取出每个键的值
        for (String key : keys) {
            Object value = redisCache.getCacheList(key);
            System.out.println(value); // 打印出每个键对应的值
            list.add(value);
        }
        return list;
    }

    //移除redis中的代理申请
    public void removeUserFromAgentApply(Integer superId, Integer userId, Integer agentId) {
        List<Integer> cacheList = redisCache.getCacheList("agentApply:" + superId + ":" + agentId + ":");
        if (cacheList != null) {
            System.out.println("-1---------------cacheList:" + cacheList);
            cacheList.remove(userId);
            System.out.println("-2---------------cacheList:" + cacheList);

            if (!cacheList.isEmpty()) {
                System.out.println("cacheList不为空----------更新键值");
                redisCache.deleteObject("agentApply:" + superId + ":" + agentId + ":");
                redisCache.setCacheList("agentApply:" + superId + ":" + agentId + ":", cacheList);
            } else {
                System.out.println("cacheList为空----------删除键值");
                // 如果列表为空，可以选择删除整个缓存对象
                redisCache.deleteObject("agentApply:" + superId + ":" + agentId + ":");
            }
        }
    }

    //判断是否已经申请过
    public boolean isApply(Integer superId, Integer userId, Integer agentId) {
        List<Integer> cacheList = redisCache.getCacheList("agentApply:" + superId + ":" + agentId + ":");
        if (cacheList != null) {
            if (cacheList.contains(userId)) {
                return true;
            }
        }
        return false;
    }

}
